import json
import time

import requests as req

from codes.commons.configs import easiest_common_headers as common_headers
from codes.match1.md5_maker import MakerMd5

maker_md5 = MakerMd5()


def request_pages():
    price_total = 0
    count = 0
    for i in range(5):
        page_content = request_html_by_page(i + 1)
        print(f'获取第【{i + 1}】页数据：{page_content}')
        con_obj = json.loads(page_content)
        for d in con_obj['data']:
            price_total += d['value']
            count += 1
    print('合计总价为: ', price_total)
    print('平均价格为：', price_total / count)


def request_html_by_page(page: int):
    url = 'http://match.yuanrenxue.com/api/match/1'
    timestamp = get_plus_timestamp()
    maker_md5.hex_md5(timestamp)
    m_params = maker_md5.hex_md5(str(timestamp)) + '丨' + str(int(timestamp / 1000))
    params = {
        'm': m_params,
        'page': page
    }
    resp = req.get(url=url, params=params, headers=common_headers)
    if 200 == resp.status_code:
        return resp.text
    else:
        print(f'其他状态码:{resp.status_code}, 页面: {resp.text}')
        return None


def get_plus_timestamp():
    return int(time.time()) * 1000 + 100000000


if __name__ == '__main__':
    request_pages()
